package leetcode.binaryTree;

import utils.printer.BinaryTrees;
import datastructure.tree.BinarySearchTree;
import datastructure.tree.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @Description: https://leetcode.cn/problems/binary-tree-level-order-traversal/
 * 给你二叉树的根节点 root ，返回其节点值的 层序遍历 。 （即逐层地，从左到右访问所有节点）。
 * @Author Ammar
 * @Create 2023/3/29 17:51
 */
public class _102_二叉树的层序遍历 {
    public static List<List<Integer>> levelOrder(TreeNode<Integer> root) {
        List<List<Integer>> datas = new ArrayList<>();
        if (root == null) return datas;
        Queue<TreeNode<Integer>> queue = new LinkedList<>();
        queue.offer(root);
        while (queue.size() != 0) {
            List<Integer> data = new ArrayList<>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode<Integer> node = queue.poll();
                data.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            datas.add(data);
        }
        return datas;
    }

    public static void main(String[] args) {
        Integer[] data = new Integer[]{
                7, 4, 9, 2, 5, 8 ,11, 3, 12, 1
        };
        BinarySearchTree<Integer> binarySearchTree = new BinarySearchTree<>();
        for (int i = 0; i < data.length; i++) {
            binarySearchTree.add(data[i]);
        }
        BinaryTrees.print(binarySearchTree);
        List<List<Integer>> lists = levelOrder(binarySearchTree.getRoot());
        lists.forEach(System.out::print);
    }
}
